package excel

import (
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"github.com/xuri/excelize/v2"
)

type Exporter struct {
	File  *excelize.File
	Sheet string
}

func NewExcelExporter() *Exporter {
	exptr := new(Exporter)
	exptr.Sheet = "Sheet1"
	exptr.File = excelize.NewFile()
	return exptr
}

func (this *Exporter) WriteTo(x int, y int, data interface{}) error {
	pos, e := excelize.CoordinatesToCellName(x, y, false)
	if e != nil {
		ez.Debug(fmt.Sprintf("坐标系转换错误，x=%d,y=%d", x, y))
		return e
	}
	//--写入年
	e = this.File.SetCellValue(this.Sheet, pos, data)
	if e != nil {
		ez.Debug(fmt.Sprintf("数据写入错误，x=%d,y=%d,data=%v", x, y, data))
		return e
	}
	return nil
}

func (this *Exporter) createExcelFileForDownLoad(data [][]interface{}) {
	for rowIndex, row := range data {
		for colIndex, col := range row {
			ez.Try(this.WriteTo(rowIndex+1, colIndex+1, col))
		}
	}
}

func (this *Exporter) CreateFile(path string) error {
	e := this.File.SaveAs(path)
	if e != nil {
		ez.Debug(e)
		return e
	}
	return nil
}
